package com.zwl.minio.config;


import com.zwl.execption.ZWLException;
import com.zwl.minio.service.FileService;
import com.zwl.minio.service.impl.FileServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Author:huzhongkui
 * Date: 2024-10-22 星期二 15:45:01
 * Description:  minio的自动配置类
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio",value = "enable",havingValue = "true")
public class MinioAutoconfiguration {

    Logger logger = LoggerFactory.getLogger(MinioAutoconfiguration.class);
    @Autowired
    private MinioProperties minioProperties;

    /**
     * 定义一个Minio的Bean对象
     */

    @Bean
    public MinioClient minioClient() {

        try {
            // 1.创建minio的客户端
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();
            // 2.判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            // 2.1 桶没找到  创一个新的桶
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
                // 2.2 桶找到了
            } else {
                logger.info("Bucket  temp is already exists.");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("MinIO客户端创建失败，详细信息：", e);
            throw new ZWLException(201, "minio客户端创建失败");
        }

    }


    @Bean
    public FileService fileService() {
        return new FileServiceImpl();
    }


}
